// --------------------------
// equipment/Equipment.ts
// --------------------------
import { EAffixType, EItemQuality, EItemType, EItemAffix, IItem, IAffixConfig, AffixPool, EEquipmentType, EAffixGroup, EquipmentTypeToAffixGroups, WuxingAffixPool } from "./Item";
import { EPlayerType, EWuxing } from "../Config/Enum";


import { _decorator, Component, Node, Color, randomRangeInt } from 'cc';
import { Gem, IGem } from "./Gem";
import { Util } from "../Util";
import { Core } from "../Core/Core";



export interface IEquipment extends IItem {
    // 装备特有属性
    equipmentType: EEquipmentType; // 装备具体类型
    gemSlots: number; // 宝石插槽数量
    profession: EPlayerType[]; // 职业限制
    affixes?: EItemAffix[]; // 词缀列表
    affixes_wuxing?: EItemAffix[]; // 五行属性词缀
    gems?: IGem[]; // 镶嵌的宝石
    level?: number; // 强化等级
    isEquipped?: boolean; // 是否已装备
    score: number; // 添加 score 属性
    price: number; // 物品价格
    wuxing?: EWuxing; // 五行属性
    ap?: number; // 攻击力
    dp?: number; // 防御力
}

// 装备类实现 IEquipment 接口
export class Equipment implements IEquipment {
    // IItem 实现
    id: string;
    uid: string = ''; // 唯一ID，运行时生成
    name: string;
    count: number;
    icon: string;
    itemType: EItemType = EItemType.Equipment; // 固定为装备大类
    desc: string;
    //stackable: boolean = false; // 装备不可堆叠
    quality: EItemQuality; // 装备品质
    score: number; // 装备评分
    price: number;
    wuxing: EWuxing;
    ap: number=0; // 攻击力
    dp: number=0; // 防御力
    

    // IEquipment 特有属性
    equipmentType: EEquipmentType;
    //possibleAffixes: IAffixConfig[];
    //maxAffixCount: number;
    gemSlots: number;
    //color: Color;
    profession: EPlayerType[];
    affixes: EItemAffix[]; // 普通词缀列表
    affixes_wuxing: EItemAffix[]; // 五行属性词缀
    gems: IGem[] = [];
    level: number = 0;
    isEquipped: boolean = false;

    constructor(template: IEquipment) {
        if (template) {
            this.id = template.id;
            this.uid = template.uid || Util.generateRandomId(); // 生成唯一ID
            this.name = template.name;
            this.count = template.count || 1;
            this.quality = template.quality || EItemQuality.Common;
            this.desc = template.desc || "";
            this.icon = template.icon;
            //this.color = template.color;
            this.wuxing = template.wuxing || this.getRandomWuxing();

            this.profession = template.profession || [];
            this.equipmentType = template.equipmentType;
            // this.possibleAffixes = template.possibleAffixes || [];
            // this.maxAffixCount = template.maxAffixCount || 4;
            this.affixes = template.affixes || [];
            this.affixes_wuxing = template.affixes_wuxing || [];
            this.gems = template.gems || [];
            this.level = template.level || 0;
            this.isEquipped = template.isEquipped || false;
            this.getRandomAPDP();

            // 如果没有词缀，则随机生成普通词缀
            if (this.affixes.length === 0) {
                this.generateRandomAffixes();
            }
            // 如果没有五行属性词缀，则随机生成
            if (this.affixes_wuxing.length === 0) {
                this.generateRandomWuxingAffixes();
            }
            // 随机生成词缀



            

            // 优先使用模板中的宝石插槽配置
            //this.gemSlots = template.gemSlots;
            
            // 如果模板未指定插槽数量，则根据品质生成
            // if (this.gemSlots === undefined) {
            //     console.warn(`装备 ${this.name} 未指定宝石插槽数量，自动根据品质生成`);
            this.gemSlots = this.generateGemSlotsByQuality();
            //}

            this.score =this.calculateScore(); // 计算评分
            this.price =this.score; // 价格等于评分
        }
    }

        // 根据品质生成宝石插槽数量 (1-3)
    private generateGemSlotsByQuality(): number {
        switch (this.quality) {
            case EItemQuality.Common:
                return 0
            case EItemQuality.Uncommon:
                return 0
            case EItemQuality.Rare:
                return randomRangeInt(0, 1); // 稀有装备1-2个
            case EItemQuality.Epic:
                return randomRangeInt(0, 2); // 史诗装备固定2个
            case EItemQuality.Legendary:
                return randomRangeInt(0, 3); // 传奇装备2-3个
            case EItemQuality.Artifact:
                return randomRangeInt(1, 3); // 神器固定3个
            default:
                return 0;
        }
    }

    getRandomWuxing(): EWuxing {
        const keys = Object.keys(EWuxing).filter(key => isNaN(Number(key)));
        const randomKey = keys[Math.floor(Math.random() * keys.length)] as keyof typeof EWuxing;
        return EWuxing[randomKey];
    }

    getRandomAPDP() {
        //如果this.equipmentType类型是武器、玉佩、戒指、护腕、项链，则生成攻击力，否则不生成
        if (this.equipmentType === EEquipmentType.Weapon || this.equipmentType === EEquipmentType.Pendant || this.equipmentType === EEquipmentType.Ring || this.equipmentType === EEquipmentType.Bracers|| this.equipmentType === EEquipmentType.Necklace) {
            this.ap = randomRangeInt(1, 5) * this.quality;
        }else {
            this.dp = randomRangeInt(1, 5) * this.quality;
        }
    }


    // 序列化装备数据
    getPackage(): any {
        console.log("五行问题排查 Equipment getPackage this.wuxing:", this.wuxing);
        return {
            __type: 'Equipment', // 添加类型标识
            id: this.id,
            uid: this.uid, // 添加唯一ID
            name: this.name,
            count: this.count,
            itemType: this.itemType,
            quality: this.quality,
            icon: this.icon,
            desc: this.desc,
            equipmentType: this.equipmentType,
            gemSlots: this.gemSlots,
            profession: this.profession,
            level: this.level,
            isEquipped: this.isEquipped,
            score: this.score,
            price: this.price,
            wuxing: this.wuxing,
            ap: this.ap,
            dp: this.dp,
            
            // 序列化词缀
            affixes: this.affixes.map(affix => ({
                type: affix.type,
                value: affix.value,
                isPercentage: affix.isPercentage,
                description: affix.description
            })),

            // 序列化五行词缀
            affixes_wuxing: this.affixes_wuxing.map(affix => ({
                type: affix.type,
                value: affix.value,
                isPercentage: affix.isPercentage,
                description: affix.description,
                isActive: affix.isActive
            })),

            
            
            // 序列化宝石
            gems: this.gems.map(gem => ({
                id: gem.id,
                gemType: gem.gemType,
                affixes: gem.affixes.map(affix => ({
                    type: affix.type,
                    value: affix.value,
                    isPercentage: affix.isPercentage,
                    description: affix.description
                })),
            }))
        };
    }


    // 从序列化数据恢复装备
    setPackage(data: any): void {
        console.log("五行问题排查 Equipment setPackage this.wuxing:", this.wuxing);
        if (!data) return;
        
        // 恢复基本属性
        this.id = data.id;
        this.uid = data.uid || ''; // 添加唯一ID
        this.name = data.name;
        this.count = data.count || 1;
        this.itemType = data.itemType;
        this.quality = data.quality;
        this.icon = data.icon;
        this.desc = data.desc || "";
        this.equipmentType = data.equipmentType;
        this.gemSlots = data.gemSlots;
        this.profession = data.profession || [EPlayerType.Shaolin];
        this.level = data.level || 0;
        this.isEquipped = data.isEquipped || false;
        this.price = data.price
        this.wuxing = data.wuxing || this.getRandomWuxing();
        this.score = data.score || this.calculateScore(); // 计算评分
        this.ap = data.ap || 0;
        this.dp = data.dp || 0;

        
        // // 恢复颜色
        // if (data.color) {
        //     this.color = Color.fromHEX(new Color(), data.color);
        // }
        
        // 恢复词缀
        this.affixes = [];
        if (Array.isArray(data.affixes)) {
            this.affixes = data.affixes.map((affixData: any) => ({
                type: affixData.type,
                value: affixData.value,
                isPercentage: affixData.isPercentage,
                description: affixData.description
            }));
        }

        // 恢复五行词缀
        this.affixes_wuxing = [];
        if (Array.isArray(data.affixes_wuxing)) {
            this.affixes_wuxing = data.affixes_wuxing.map((affixData: any) => ({
                type: affixData.type,
                value: affixData.value,
                isPercentage: affixData.isPercentage,
                description: affixData.description,
                isActive: affixData.isActive
            }))
        }
        
        // 恢复宝石
        this.gems = [];
        if (Array.isArray(data.gems)) {
            this.gems = data.gems.map((gemData: any) => 
                new Gem({
                    id: gemData.id,
                    uid: gemData.uid || '', // 添加唯一ID
                    name: gemData.name || "", // 添加默认值
                    count: gemData.count || 1,
                    icon: gemData.icon || "",
                    desc: gemData.desc || "",
                    quality: gemData.quality || EItemQuality.Common,
                    gemType: gemData.gemType,
                    price: gemData.price || 0,
                                    // 添加缺少的itemType属性
                    itemType: EItemType.Gem, // 这是关键修复
                    affixes: gemData.affixes ? gemData.affixes.map((affix: any) => ({
                        type: affix.type,
                        value: affix.value,
                        isPercentage: affix.isPercentage,
                        description: affix.description
                    })) : []
                })
            );
        }
    }

    // get score(): number {
    //     return this.getScore();
    // }

    calculateScore(): number {
        //console.log(`计算装备 ${this.name} 的评分this.getScore()`,this.getScore());
        return this.getScore();
    }

    calculatePrice(): number {
        return this.getScore();
    }

    // 强化装备
/**
 * 强化方法，用于提升物品的等级和相关属性
 * @returns {boolean} 强化成功返回true，达到最大等级返回false
 */
public strengthen(): boolean {
    const maxLevel = 10; // 定义最大强化等级为10
    if (this.level >= maxLevel) return false; // 如果当前等级已达到最大值，则返回强化失败
    
    this.level++; // 强化等级加1
    // 基础提升 + 百分比提升，确保每次都有可见提升
    const baseGain = 1; // 每次强化至少提升1点
    const percentageRate = this.getStrengthenRate();
    
    // 基础AP/DP提升（根据品质有不同系数）
    const strengthenRate = this.getStrengthenRate();
    console.log(`装备强化装备 ${this.name} 强化，品质: ${this.quality}，提升系数: ${strengthenRate}, 当前等级: ${this.level}, AP: ${this.ap}, DP: ${this.dp}`);
    if (this.ap) {
        const percentageGain = Math.max(1, Math.round(this.ap * percentageRate));
        this.ap += baseGain + percentageGain;
    }
    if (this.dp) {
        const percentageGain = Math.max(1, Math.round(this.dp * percentageRate));
        this.dp += baseGain + percentageGain;
    }
    console.log(`装备强化装备 ${this.name} 强化，品质: ${this.quality}，提升系数: ${strengthenRate}, 当前等级: ${this.level}, AP: ${this.ap}, DP: ${this.dp}`);


    // 2. 强化词缀（新增）
    this.enhanceAffixes();

    
    // 小概率额外提升一个随机词缀（肉鸽元素）TODO
    // if (Math.random() < 0.2) { // 20%几率
    //     this.randomEnhanceOneAffix();
    // }
    
    this.score = this.calculateScore();
    this.price = this.score;

    // 如果装备是被装备状态，更新角色属性
    if (this.isEquipped) {
        console.log("强化的是被装备状态的装备，更新角色属性")
        Core.Instance.players.get(Core.Instance.currentPlayer).calculateAttributes(); // 更新角色属性
    }



    Core.Instance.save(); // 保存数据
    
    return true;
}

private getStrengthenRate(): number {
    // 品质越高，强化收益越大
    const baseRates = {
        [EItemQuality.Common]: 0.08,
        [EItemQuality.Uncommon]: 0.09, 
        [EItemQuality.Rare]: 0.10,
        [EItemQuality.Epic]: 0.11,
        [EItemQuality.Legendary]: 0.12,
        [EItemQuality.Artifact]: 0.15
    };
    return baseRates[this.quality] || 0.1;
}

public getStrengthenCost(): number {
    const baseCost = 100;
    return baseCost * this.level * (this.quality + 1);
}

public getStrengthenSuccessRate(): number {
    const baseRate = 0.9; // 90%基础成功率
    const levelPenalty = this.level * 0.05; // 每级降低5%
    return Math.max(0.5, baseRate - levelPenalty); // 最低50%
}

private enhanceAffixes(): void {
    // 使用对象快速查找
    const enhanceableTypes: { [key: string]: boolean } = {
        [EAffixType.Attack]: true,
        [EAffixType.Defense]: true,
        [EAffixType.Strength]: true,
        [EAffixType.Agility]: true,
        [EAffixType.Intelligence]: true,
        [EAffixType.Vitality]: true,
        [EAffixType.AllBaseAttributes]: true,

    };
    
    for (const affix of this.affixes) {
        if (enhanceableTypes[affix.type]) {
            const enhanceValue = this.getAffixEnhanceValue(affix);
            affix.value += enhanceValue;
            
            affix.description = this.getAffixDescription(
                affix.type, 
                affix.value, 
                affix.isPercentage
            );
            
            console.log(`词缀强化：${affix.description}`);
        }
    }
}

private getAffixEnhanceValue(affix: EItemAffix): number {
    // 根据品质和等级决定强化幅度
    const baseRate = 0.02; // 2%的基础提升
    const qualityMultiplier = this.quality * 0.5;
    const levelMultiplier = this.level * 0.1;
    
    let enhanceValue: number;
    
    if (affix.isPercentage) {
        enhanceValue = affix.value * baseRate * (1 + qualityMultiplier + levelMultiplier);
    } else {
        // 固定值词缀，基于原始值的百分比提升
        enhanceValue = Math.max(1, Math.round(affix.value * baseRate * (1 + qualityMultiplier)));
    }
    
    return enhanceValue;
}


// 强化惊喜，随机提升一个词缀的数值
private randomEnhanceOneAffix(): void {
    if (this.affixes.length === 0) return;
    
    const randomAffix = this.affixes[Math.floor(Math.random() * this.affixes.length)];
    const enhanceRate = 0.05; // 5%提升
    
    if (randomAffix.isPercentage) {
        randomAffix.value *= (1 + enhanceRate);
    } else {
        randomAffix.value = Math.round(randomAffix.value * (1 + enhanceRate));
    }
    
    // 更新描述
    randomAffix.description = this.getAffixDescription(
        randomAffix.type, 
        randomAffix.value, 
        randomAffix.isPercentage
    );
    
    console.log(`强化惊喜！${randomAffix.description}`);
}



        // 获取最大强化等级（根据品质）
    private getMaxLevel(): number {
        switch (this.quality) {
            case EItemQuality.Common: return 5;
            case EItemQuality.Uncommon: return 8;
            case EItemQuality.Rare: return 12;
            case EItemQuality.Epic: return 15;
            case EItemQuality.Legendary: return 20;
            case EItemQuality.Artifact: return 25;
            default: return 10;
        }
    }

        // 镶嵌宝石
    public equipGem(gem: Gem): boolean {
        if (this.gems.length >= this.gemSlots) return false;
        
        this.gems.push(gem);
        return true;
    }


    // 生成普通词缀
    private generateRandomAffixes() {
        const affixCount = this.getAffixCountByQuality();
        
        // 获取当前装备类型允许的词缀组
        const allowedGroups = EquipmentTypeToAffixGroups[this.equipmentType] || [EAffixGroup.Universal];
        //console.log(`1111111111允许的词缀组: ${allowedGroups}`);

        const possibleAffixes = AffixPool.filter(affix => 
            affix.rarity <= this.quality && 
            affix.groups.some(group => allowedGroups.indexOf(group) !== -1) // 只依赖组进行过滤
        );

        //console.log(`1111111111可能的词缀数量: ${possibleAffixes.length}`);
        
        // 权重选择词缀
        for (let i = 0; i < affixCount; i++) {
            const selectedAffix = this.selectWeightedAffix(possibleAffixes);
            if (!selectedAffix) continue;
            
            // 创建实际词缀
            const value = this.calculateAffixValue(selectedAffix);
            this.affixes.push({
                type: selectedAffix.type,
                value: value,
                isPercentage: selectedAffix.isPercentage,
                description: this.getAffixDescription(selectedAffix.type, value, selectedAffix.isPercentage)
            });

        //console.log(`111111111111111生成词缀: ${this.affixes[this.affixes.length - 1].description}`);
        }
    }
    // 生成五行词缀
    private generateRandomWuxingAffixes() {
        const affixCount = this.getWuxingAffixCountByQuality()
        console.log(`1111111111生成 ${this.name} 的随机五行词缀，数量: ${affixCount}`);
        
        // 获取当前装备类型允许的词缀组
        const allowedGroups = EquipmentTypeToAffixGroups[this.equipmentType] || [EAffixGroup.Universal];
        console.log(`1111111111允许的五行词缀组: ${allowedGroups}`);
        
        const possibleAffixes = WuxingAffixPool.filter(affix => 
            affix.rarity <= this.quality && 
            affix.groups.some(group => allowedGroups.indexOf(group) !== -1) &&
            affix.wuxing === this.wuxing || affix.wuxing === undefined
        );

        console.log(`1111111111可能的五行词缀: possibleAffixes`,possibleAffixes);

        // 如果没有找到合适的词缀，直接返回
        if (possibleAffixes.length === 0) {
            console.warn(`未找到适合装备 ${this.name} (五行:${this.wuxing}) 的五行词缀`);
            return;
        }
        
        // 权重选择词缀
        for (let i = 0; i < affixCount; i++) {
            const selectedAffix = this.selectWeightedAffix(possibleAffixes);
            if (!selectedAffix) continue;
            
            // 创建实际词缀
            const value = this.calculateAffixValue(selectedAffix);
            this.affixes_wuxing.push({
                type: selectedAffix.type,
                value: value,
                isPercentage: selectedAffix.isPercentage,
                description: this.getAffixDescription(selectedAffix.type, value, selectedAffix.isPercentage),
                isActive: false,
                //wuxing: selectedAffix.wuxing
            });

        console.log(`111111111111111生成五行词缀: ${this.affixes_wuxing[this.affixes_wuxing.length - 1].description}`);
        }
    }



    // 根据品质决定普通词缀数量
    private getAffixCountByQuality(): number {
        switch (this.quality) {
            case EItemQuality.Common: return 1;
            case EItemQuality.Uncommon: return randomRangeInt(1, 3);
            case EItemQuality.Rare: return randomRangeInt(3, 4);
            case EItemQuality.Epic: return randomRangeInt(3, 5);
            case EItemQuality.Legendary: return randomRangeInt(4,6);
            case EItemQuality.Artifact: return randomRangeInt(5,7)
            default: return 1;
        }
    }

        // 根据品质决定五行词缀数量
    private getWuxingAffixCountByQuality(): number {
        switch (this.quality) {
            case EItemQuality.Common: return 0;
            case EItemQuality.Uncommon: return 0;
            case EItemQuality.Rare: return randomRangeInt(0, 2);
            case EItemQuality.Epic: return randomRangeInt(1, 3);
            case EItemQuality.Legendary: return 2
            case EItemQuality.Artifact: return 2
            default: return 2;
        }
    }

// 修改selectWeightedAffix方法，考虑词缀稀有度与装备品质的匹配度
    private selectWeightedAffix(affixes: IAffixConfig[]): IAffixConfig | null {
        if (affixes.length === 0) return null;
        
        // 计算考虑稀有度匹配的权重
        const weightedAffixes = affixes.map(affix => {
            let weight = affix.weight;
            
            // 根据稀有度与装备品质的匹配度调整权重
            const rarityDiff = Math.abs(affix.rarity - this.quality);
            if (rarityDiff === 0) {
                // 完美匹配，增加权重
                weight *= 1.5;
            } else if (rarityDiff === 1) {
                // 接近匹配，正常权重
                weight *= 1.0;
            } else {
                // 不匹配，降低权重
                weight *= 0.5;
            }
            
            return { affix, weight };
        });
        
        const totalWeight = weightedAffixes.reduce((sum, wa) => sum + wa.weight, 0);
        let random = Math.random() * totalWeight;
        
        for (const weightedAffix of weightedAffixes) {
            random -= weightedAffix.weight;
            if (random <= 0) return weightedAffix.affix;
        }
        
        return weightedAffixes[0].affix;
    }

        // 计算词缀值（考虑品质加成）
    private calculateAffixValue(affix: IAffixConfig): number {
        // 基础值范围
        let minValue = affix.minValue;
        let maxValue = affix.maxValue;
        
        // // 根据品质调整数值范围
        // const qualityMultiplier = this.getQualityMultiplier(affix.rarity);
        // // minValue *= qualityMultiplier;
        // // maxValue *= qualityMultiplier;
        // const adjustedMin = minValue * qualityMultiplier;
        // const adjustedMax = Math.min(maxValue * qualityMultiplier, affix.maxValue * 1.5); // 设置上限
        
        // 生成随机值，如果是百分比，则返回，如果是整数，则四舍五入
        let result = this.getRandomValueInRange(minValue, maxValue);
        if (affix.isPercentage) {
            return result;
        }else {
            return Math.round(result);
        }
    }
        
    // 根据品质和词缀稀有度获取 multiplier
    private getQualityMultiplier(affixRarity: number): number {
        // 基础 multiplier (1.0-2.0 基于装备品质)
        let baseMultiplier = 1.0 + (this.quality - 1) * 0.2;
        
        // 如果词缀稀有度高于装备品质，适当降低 multiplier
        if (affixRarity > this.quality) {
            baseMultiplier *= 0.8;
        }
        // 如果词缀稀有度低于装备品质，适当增加 multiplier
        else if (affixRarity < this.quality) {
            baseMultiplier *= 1.2;
        }
        
        return baseMultiplier;
    }



    // 在范围内生成随机值
    private getRandomValueInRange(min: number, max: number): number {
        return min + Math.random() * (max - min)
    }

    // // 获取词缀描述
    private getAffixDescription(type: EAffixType, value: number, isPercentage: boolean): string {
        const formattedValue = isPercentage ? 
            `${(value * 100).toFixed(0)}%` : 
            value.toFixed(0);
        // const formattedValue_int = isPercentage ? 
        //     `${(value * 100).toFixed(0)}%` : 
        //     value.toFixed(0);

        
        switch (type) {
            // 攻击类词缀
            case EAffixType.Attack: return `攻击力 ${formattedValue}`;
            case EAffixType.CriticalChance: return `会心一击率 ${formattedValue}`;
            case EAffixType.CriticalDamage: return `会心一击伤害 ${formattedValue}`;
            case EAffixType.Accuracy: return `命中率 ${formattedValue}`;
            case EAffixType.AttackSpeed: return `攻击速度 ${formattedValue}`;
            case EAffixType.IgnoreDefense: return `无视防御 ${formattedValue}`;
            case EAffixType.LifeSteal: return `吸血 ${formattedValue}`;
            case EAffixType.AttackRange: return `攻击范围 ${formattedValue}`;
            case EAffixType.PenetrateCount: return `穿透 +${formattedValue}`;
            case EAffixType.PenetratePercent: return `穿透伤害 ${formattedValue}`;
            case EAffixType.ComboChance: return `连击 ${formattedValue}`;
            case EAffixType.SkillEnhance: return `武学伤害 ${formattedValue}`;

            // 防御类词缀
            case EAffixType.Defense: return `防御力 ${formattedValue}`;
            case EAffixType.Hp: return `生命值 ${formattedValue}`;
            case EAffixType.Dodge: return `闪避率 ${formattedValue}`;
            case EAffixType.HpRegen: return `生命回复 ${formattedValue}`;


            //通用词缀
            case EAffixType.SkillLevel: return `全武学等级 +${formattedValue}`;
            case EAffixType.Skill1Level: return `武学1等级 +${formattedValue}`;
            case EAffixType.Skill2Level: return `武学2等级 +${formattedValue}`;
            case EAffixType.Skill3Level: return `武学3等级 +${formattedValue}`;

            case EAffixType.CDR: return `调息时间缩减 ${formattedValue}`;
            case EAffixType.Strength: return `力量 ${formattedValue}`;
            case EAffixType.Agility: return `身法 ${formattedValue}`;
            case EAffixType.Intelligence: return `悟性 ${formattedValue}`;
            case EAffixType.Vitality: return `体质 ${formattedValue}`;
            case EAffixType.InnerPower: return `内力 ${formattedValue}`;
            case EAffixType.AllBaseAttributes: return `全属性 ${formattedValue}`;
            case EAffixType.WuxingEnhance: return `五行增强 ${formattedValue}`;
            case EAffixType.Speed: return `移动速度 ${formattedValue}`;


            // 功能类词缀
            case EAffixType.Coin: return `钱币获取 ${formattedValue}`;
            case EAffixType.Exp: return `修为值获取 ${formattedValue}`;
            case EAffixType.Reown: return `声望获取 ${formattedValue}`;
            case EAffixType.MF: return `物品掉落率 +${formattedValue}`;


    // 金木水火土专用五行词缀

    case EAffixType.Jin_DamageToKnockback: return `对击退目标伤害 ${formattedValue}`;
    case EAffixType.Jin_DamageToWoodEnemy: return `对木系敌寇伤害 ${formattedValue}`;
    case EAffixType.Jin_FogDaySkillDamage: return `雾天武学伤害 ${formattedValue}`;

    case EAffixType.Mu_DamageToPoisoned: return `对中毒目标伤害 ${formattedValue}`;
    case EAffixType.Mu_DamageToEarthEnemy: return `对土系敌寇伤害 ${formattedValue}`;
    case EAffixType.Mu_CloudyDaySkillDamage: return `阴天武学伤害 ${formattedValue}`;

    case EAffixType.Shui_DamageToSlowed: return `对迟缓目标伤害 ${formattedValue}`;
    case EAffixType.Shui_DamageToFireEnemy: return `对火系敌寇伤害 ${formattedValue}`;
    case EAffixType.Shui_RainDaySkillDamage: return `雨天武学伤害 ${formattedValue}`;

    case EAffixType.Huo_DamageToBurning: return `对灼烧目标伤害 ${formattedValue}`;
    case EAffixType.Huo_DamageToMetalEnemy: return `对金系敌寇伤害 ${formattedValue}`;
    case EAffixType.Huo_SunnyDaySkillDamage: return `晴天武学伤害 ${formattedValue}`;

    case EAffixType.Tu_DamageToStunned: return `对晕眩目标伤害 ${formattedValue}`;
    case EAffixType.Tu_DamageToWaterEnemy: return `对水系敌寇伤害 ${formattedValue}`;
    case EAffixType.Tu_WindDaySkillDamage: return `风天武学伤害 ${formattedValue}`;

    // 通用五行词缀描述
    case EAffixType.WallHPFullAttack: return `城墙满耐久攻击 ${formattedValue}`;
    case EAffixType.WallHPFullAttackSpeed: return `城墙满耐久攻速 ${formattedValue}`;
    case EAffixType.WallHPLowAttack: return `城墙低耐久攻击 ${formattedValue}`;
    case EAffixType.WallHPLowAttackSpeed: return `城墙低耐久攻速 ${formattedValue}`;
    case EAffixType.DamageIncreaseToElite: return `对精英伤害 ${formattedValue}`;
    case EAffixType.DamageIncreaseToGeneral: return `对将军伤害 ${formattedValue}`;
    case EAffixType.DamageIncreaseToSoldier: return `对小兵伤害 ${formattedValue}`;
    case EAffixType.DamageIncreaseToHighHP: return `对高血量伤害 ${formattedValue}`;
    case EAffixType.DamageIncreaseToLowHP: return `对低血量伤害 ${formattedValue}`;
    case EAffixType.DamageIncreaseToCCTarget: return `对受控目标伤害 ${formattedValue}`;
    case EAffixType.RageRegen: return `怒气回复 +${formattedValue}`;
    case EAffixType.DamageIncrease25Strength: return `附加力量${formattedValue}的伤害`;
    case EAffixType.DamageIncrease25Agility: return `附加身法${formattedValue}的伤害 `;
    case EAffixType.DamageIncrease25Intelligence: return `附加悟性${formattedValue}的伤害`;



            default: return "未知属性";
        }
    }



        // 计算单件装备总属性加成
    // 修改 calculateTotalStats 方法中的宝石处理部分
    // public calculateTotalStats(): Record<EAffixType, number> {
    //     const fixedStats: Partial<Record<EAffixType, number>> = {};
    //     const percentageStats: Partial<Record<EAffixType, number>> = {};
    //     const totalStats: Record<EAffixType, number> = {} as any;

    //     // 使用 Object.keys() 替代 Object.values()
    //     const affixTypeKeys = Object.keys(EAffixType) as (keyof typeof EAffixType)[];
        
    //     // 初始化所有属性类型
    //     affixTypeKeys.forEach(key => {
    //         const type = EAffixType[key];
    //         fixedStats[type] = 0;
    //         percentageStats[type] = 0;
    //     });

    //     // 处理装备自身词缀
    //     for (const affix of this.affixes) {
    //         if (affix.isPercentage) {
    //             percentageStats[affix.type]! += affix.value; 
    //         } else {
    //             fixedStats[affix.type]! += affix.value;
    //         }
    //     }

    //     // 处理五行词缀（已激活的）
    //     for (const affix of this.affixes_wuxing) {
    //         if (!affix.isActive) continue;
    //         if (affix.isPercentage) {
    //             percentageStats[affix.type]! += affix.value;
    //         } else {
    //             fixedStats[affix.type]! += affix.value;
    //         }
    //         console.log(`五行词缀生效(百分比的): ${affix.type},${percentageStats[affix.type]}`);
    //         console.log(`五行词缀生效(普通数值的): ${affix.type},${fixedStats[affix.type]}`);


    //     }

    //     // 处理宝石 - 修复这里
    //     for (const gem of this.gems) {
    //         // 遍历宝石的所有词缀
    //         for (const affix of gem.affixes) {
    //             if (affix.isPercentage) {
    //                 percentageStats[affix.type]! += affix.value;
    //             } else {
    //                 fixedStats[affix.type]! += affix.value;
    //             }
    //         }
    //     }

    //     // 合并属性：直接相加
    //     affixTypeKeys.forEach(key => {
    //         const type = EAffixType[key];
    //         const fixedValue = fixedStats[type] || 0;
    //         const percentageValue = percentageStats[type] || 0;
    //         totalStats[type] = fixedValue + percentageValue;
    //     })
    //     // affixTypeKeys.forEach(key => {
    //     //     const type = EAffixType[key];
    //     //     const fixedValue = fixedStats[type] || 0;
    //     //     const percentageValue = percentageStats[type] || 0;
    //     //     totalStats[type] = fixedValue * (1 + percentageValue);
    //     // });

    //     console.log("Single equipment total stats:", totalStats);
    //     return totalStats;
    // }
public calculateTotalStats(): {
    normalStats: Record<EAffixType, number>;
    wuxingStats: {}
} {
    const normalStats  = {} as Record<EAffixType, number>;
    const wuxingStats = {} 


        // 首先添加装备本身的 AP 和 DP 到对应的词缀类型
    if (this.ap && this.ap > 0) {
        normalStats[EAffixType.Attack] = (normalStats[EAffixType.Attack] || 0) + this.ap;
    }
    
    if (this.dp && this.dp > 0) {
        normalStats[EAffixType.Defense] = (normalStats[EAffixType.Defense] || 0) + this.dp;
    }


    // 处理装备自身普通词缀
    for (const affix of this.affixes) {
        if (affix.value !== 0) {
            const currentValue = normalStats[affix.type];
            if (currentValue === undefined) {
                normalStats[affix.type] = affix.value;
            } else {
                normalStats[affix.type] = currentValue + affix.value;
            }
        }
    }



    // 处理五行词缀（已激活的）
    for (const affix of this.affixes_wuxing) {
        if (!affix.isActive || affix.value === 0) continue;

        // 某些词缀是放到普通属性里计算的
        if (
            affix.type === EAffixType.RageRegen ||
            affix.type === EAffixType.DamageIncrease25Strength ||
            affix.type === EAffixType.DamageIncrease25Agility ||
            affix.type === EAffixType.DamageIncrease25Intelligence
        ) {
            const currentValue = normalStats[affix.type];
            if (currentValue === undefined) {
                normalStats[affix.type] = affix.value;
            } else {
                normalStats[affix.type] = currentValue + affix.value;
            }
        }else {
            const currentValue = wuxingStats[affix.type];
            if (currentValue === undefined) {
                wuxingStats[affix.type] = affix.value;
            } else {
                wuxingStats[affix.type] = currentValue + affix.value;
            }
        }
        
        console.log(`五行词缀生效: ${affix.type}, 值: ${affix.value}`);
    }

    // 处理宝石（归入普通词缀）
    for (const gem of this.gems) {
        for (const affix of gem.affixes) {
            if (affix.value !== 0) {
                const currentValue = normalStats[affix.type];
                if (currentValue === undefined) {
                    normalStats[affix.type] = affix.value;
                } else {
                    normalStats[affix.type] = currentValue + affix.value;
                }
            }
        }
    }
    
    return { normalStats, wuxingStats };
}


    // 计算评分
    getScore(): number {
        let score = 0;
        
        // 1. 基础评分（品质 + 等级）
        score += this.calculateBaseScore();
        
        // 2. 词缀评分（基于标准价值单位）
        score += this.calculateAffixesScore();
        
        // 3. 宝石系统评分
        score += this.calculateGemsScore();

        console.log("装备词缀评分 score=================================:", score);
        
        return Math.round(score);
    }

    private calculateBaseScore(): number {
        // 品质评分非线性增长
        const qualityMultipliers = {
            [EItemQuality.Common]: 1,
            [EItemQuality.Uncommon]: 3,
            [EItemQuality.Rare]: 8,
            [EItemQuality.Epic]: 20,
            [EItemQuality.Legendary]: 50,
            [EItemQuality.Artifact]: 100
        };
        
        // 强化等级评分（每级增长递增）
        //const levelScore = this.level * (10 + this.level * 2);
        console.log("装备词缀评分 Base score:", qualityMultipliers[this.quality] * 50);
        return qualityMultipliers[this.quality] * 50 
    }

    private calculateAffixesScore(): number {
        let affixScore = 0;
        
        for (const affix of this.affixes) {
            // 转换为标准价值单位
            console.log("装备词缀评分 affix:", affix);

            const standardValue = this.convertToStandardValue(affix);
            console.log("装备词缀评分 standardValue:", standardValue);
            affixScore += standardValue;
        }
        console.log("装备词缀评分 AffixesScore:", affixScore);
        return affixScore;
    }

    private convertToStandardValue(affix: EItemAffix): number {
        // 定义1个标准价值单位 = 1点攻击力
        const value = affix.isPercentage ? affix.value * 100 : affix.value;
        
        // 基于游戏平衡设计的转换系数
        const conversionRates: Record<EAffixType|EAffixType, number> = {
            // 攻击类
            [EAffixType.Attack]: 1.0,
            [EAffixType.CriticalChance]: 100, // 1%暴击 ≈ 80攻击力
            [EAffixType.CriticalDamage]: 80, // 1%暴伤 ≈ 50攻击力  
            [EAffixType.AttackSpeed]: 80, // 1%攻速 ≈ 40攻击力
            [EAffixType.IgnoreDefense]: 200, // 1%穿甲 ≈ 120攻击力
            [EAffixType.Accuracy]: 50, // 1%命中 ≈ 25攻击力
            [EAffixType.AttackRange]: 200, // 1点射程 ≈ 0.5攻击力
            [EAffixType.SkillEnhance]: 150, // 1%技能增强 ≈ 150攻击力
            [EAffixType.PenetrateCount]: 100, // 穿透
            [EAffixType.PenetratePercent]: 100, // 1%穿透伤害 ≈ 100攻击力
            [EAffixType.WuxingEnhance]: 100, // 1%五行 ≈ 100攻击力
            [EAffixType.ComboChance]: 100, // 1%五行 ≈ 100攻击力

            // 防御类
            [EAffixType.Defense]: 1, // 1防御 ≈ 1攻击力
            [EAffixType.Hp]: 0.1, // 1生命 ≈ 0.1攻击力
            [EAffixType.Dodge]: 50, // 1%闪避 ≈ 50攻击力


            // 属性类
            [EAffixType.Strength]: 10, // 1力量 ≈ 8攻击力
            [EAffixType.Agility]: 10, // 1身法 ≈ 8攻击力
            [EAffixType.Intelligence]: 10, // 1悟性 ≈ 8攻击力
            [EAffixType.Vitality]: 5, // 1体质 ≈ 5攻击力
            [EAffixType.AllBaseAttributes]: 35, // 1全属性 ≈ 25攻击力
            [EAffixType.InnerPower]: 100, // 1内力 ≈ 50攻击力
    


            // 功能类
            [EAffixType.SkillLevel]: 1000, // 1技能等级 ≈ 1000攻击力
            [EAffixType.Skill1Level]: 500, // 1技能等级 ≈ 500攻击力
            [EAffixType.Skill2Level]: 500, // 1技能等级 ≈ 500攻击力
            [EAffixType.Skill3Level]: 500, // 1技能等级 ≈ 500攻击力
            [EAffixType.MF]: 500, // 1技能等级 ≈ 500攻击力


            [EAffixType.CDR]: 500, // 1%冷却 ≈ 400攻击力
            [EAffixType.Speed]: 30, // 1%移速 ≈ 30攻击力
            [EAffixType.Coin]: 100, // 1%铜钱 ≈ 20攻击力
            [EAffixType.Exp]: 100, // 1%修为 ≈ 20攻击力
            [EAffixType.Reown]: 100,
            [EAffixType.LifeSteal]: 50,
            [EAffixType.HpRegen]: 50,

            // 五行词缀
            [EAffixType.Jin_DamageToKnockback]: 60,
            [EAffixType.Jin_DamageToWoodEnemy]: 40,
            [EAffixType.Jin_FogDaySkillDamage]: 50,

            [EAffixType.Mu_DamageToPoisoned]: 60,
            [EAffixType.Mu_DamageToEarthEnemy]: 40,
            [EAffixType.Mu_CloudyDaySkillDamage]: 50,

            [EAffixType.Shui_DamageToSlowed]: 60,
            [EAffixType.Shui_DamageToFireEnemy]: 40,
            [EAffixType.Shui_RainDaySkillDamage]: 50,

            [EAffixType.Huo_DamageToBurning]: 60,
            [EAffixType.Huo_DamageToMetalEnemy]: 40,
            [EAffixType.Huo_SunnyDaySkillDamage]: 50,

            [EAffixType.Tu_DamageToStunned]: 60,
            [EAffixType.Tu_DamageToWaterEnemy]: 40,
            [EAffixType.Tu_WindDaySkillDamage]: 50,

            // 通用五行词缀评分系数
            [EAffixType.WallHPFullAttack]: 30,
            [EAffixType.WallHPFullAttackSpeed]: 30,
            [EAffixType.WallHPLowAttack]: 30,
            [EAffixType.WallHPLowAttackSpeed]: 30,
            [EAffixType.DamageIncreaseToElite]: 50,
            [EAffixType.DamageIncreaseToGeneral]: 50,
            [EAffixType.DamageIncreaseToSoldier]: 30,
            [EAffixType.DamageIncreaseToHighHP]: 40,
            [EAffixType.DamageIncreaseToLowHP]: 40,
            [EAffixType.DamageIncreaseToCCTarget]: 50,
            [EAffixType.RageRegen]: 100,
            [EAffixType.DamageIncrease25Strength]: 100,
            [EAffixType.DamageIncrease25Agility]: 100,
            [EAffixType.DamageIncrease25Intelligence]: 100,


        };
        
        const rate = conversionRates[affix.type] || 1.0;
        return value * rate;
    }

    private calculateGemsScore(): number {
        let gemScore = 0;
        
        // 已镶嵌宝石的评分
        for (const gem of this.gems) {
            for (const affix of gem.affixes) {
                const standardValue = this.convertToStandardValue(affix);
                gemScore += standardValue;
            }
        }
        
        // 空插槽的潜力分（比已镶嵌宝石价值低）
        const emptySlots = this.gemSlots - this.gems.length;
        const potentialScore = emptySlots * 200; // 每个空插槽 ≈ 200攻击力价值
        console.log("装备词缀评分宝石评分 GemsScore:", gemScore + potentialScore);
        return gemScore + potentialScore;
    }

    // 根据词缀类型返回权重
    getAffixWeight(type: EAffixType) {
        switch (type) {
            case EAffixType.Strength: return 1.0;
            case EAffixType.Agility: return 1.0;
            case EAffixType.Intelligence: return 1.0;
            case EAffixType.Vitality: return 1.0;
            case EAffixType.AllBaseAttributes: return 1.5;
            case EAffixType.Attack: return 1.0;
            case EAffixType.Defense: return 0.8;
            case EAffixType.Hp: return 1;
            case EAffixType.CriticalChance: return 50;
            case EAffixType.CriticalDamage: return 50;
            case EAffixType.Dodge: return 0.8;
            case EAffixType.Accuracy: return 20;
            case EAffixType.AttackSpeed: return 50;
            //case EAffixType.HpRegen: return 1.0;
            case EAffixType.WuxingEnhance: return 1.0;
            case EAffixType.InnerPower: return 100;
            //case EAffixType.LifeSteal: return 1.3;
            case EAffixType.IgnoreDefense: return 100;
            case EAffixType.CDR: return 300;

            // case EAffixType.WallHPFullDamage: return 1.2;
            // case EAffixType.WallHPFullAttackSpeed: return 1.2;
            // case EAffixType.DamageIncreaseToCCTarget: return 1.3;

            case EAffixType.SkillLevel: return 500;

            case EAffixType.Coin: return 1.5;
            case EAffixType.Exp: return 1.5;
            case EAffixType.Reown: return 1.5;
            // case EAffixType.SkillDamage: return 1.3;
            // case EAffixType.Speed: return 1.0;
            // case EAffixType.ElementalDamage: return 1.2;
            default: return 1.0;
        }
    }



}